package com.sz.web.context;

import com.sz.framework.trace.SzTraceIdDetectorAggregator;
import com.sz.framework.utils.CommonUtil;
import org.springframework.core.NamedThreadLocal;

/**
 * web上下文访问
 *
 * @author: yxl
 * 2025-07-23
 */
public class SzWebContextHolder {

    public static final String traceIdHeader = "Sz-Trace-Id";
    public static final String requestTypeHeader = "Sz-Request-Type";

    private static final ThreadLocal<SzWebContext> contextHolder = new NamedThreadLocal<>("SzWebContext");

    private SzWebContextHolder() {

    }

    public static void setContext(SzWebContext context) {
        contextHolder.set(context);
    }

    // 核心访问方法
    public static SzWebContext current() {
        SzWebContext ctx = contextHolder.get();
        if (ctx == null) {
            throw new IllegalStateException("无法获取WEB上下文");
        }
        return ctx;
    }

    public static SzWebContext.RequestType getRequestType() {
        return SzWebContextHolder.current().getRequestType();
    }

    public static String getHeader(String header){
        return SzWebContextHolder.current().getHeader(header);
    }

    public static String getRequestBody(){
        return SzWebContextHolder.current().getRequestBody();
    }

    public static void clear() {
        contextHolder.remove();
    }

    public static void setResponseHeader(String header, String value) {
        SzWebContextHolder.current().getResponse().setHeader(header, value);
    }

    public static String getTraceId(){
        String traceId = SzWebContextHolder.current().getHeader(SzWebContextHolder.traceIdHeader);
        if(CommonUtil.isEmpty(traceId)){
            traceId = (String)SzWebContextHolder.current().getRequest().getAttribute(SzWebContextHolder.traceIdHeader);
        }
        return traceId;
    }

}
